import {
  Breadcrumb,
  Card,
  Form,
  Radio,
  Select,
  DatePicker,
  Button,
  Table,
  Tag,
  Space,
  Modal,
} from 'antd'
import FormItem from 'antd/lib/form/FormItem'
import { Link } from 'react-router-dom'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import img404 from '@/assets/error.png'
import { useDispatch, useSelector } from 'react-redux'
import { getChannels, getArticles, delArticle } from '@/store/actions'
import { useEffect, useRef } from 'react'
import { useHistory } from 'react-router-dom'
const { confirm } = Modal

const { Option } = Select
const { RangePicker } = DatePicker

// 优化文章状态的处理
const articleStatus = {
  0: { color: 'yellow', text: '草稿' },
  1: { color: '#ccc', text: '待审核' },
  2: { color: 'green', text: '审核通过' },
  3: { color: 'red', text: '审核失败' },
}
const Article = () => {
  const history = useHistory()
  // 创建dispatch函数
  const dispatch = useDispatch()
  const { channels, page, pageSize, count, list } = useSelector(
    (state) => state.article
  )
  // 一进页面就获取数据
  useEffect(() => {
    dispatch(getChannels())
    dispatch(getArticles({}))
  }, [dispatch])

  // 上面状态栏的数据
  const status = [{}]
  // 每一行的数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover || img404} width={200} height={150} alt='' />
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => {
        const tagData = articleStatus[data]
        return <Tag color={tagData.color}>{tagData.text}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size='middle'>
            <Button
              type='primary'
              shape='circle'
              icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${data.id}`)}
            />
            <Button
              type='primary'
              danger
              shape='circle'
              icon={<DeleteOutlined />}
              onClick={() => onDeleteArticle(data.id)}
            />
          </Space>
        )
      },
    },
  ]
  const data = [
    {
      id: '8218',
      comment_count: 0,
      cover: 'http://geek.itheima.net/resources/images/15.jpg',
      like_count: 0,
      pubdate: '2019-03-11 09:00:00',
      read_count: 2,
      status: 2,
      title: 'webview离线化加载h5资源解决方案',
    },
  ]
  // useRef优化分页功能
  const paramsRef = useRef({})
  // 筛选表格数据，监听表单的数据提交
  const onSearch = (values) => {
    const { status, channel_id, date } = values
    // 将表单中选中数据，组装成接口需要的数据格式，然后，传递给接口
    const params = {}

    // 处理状态
    if (status !== -1) {
      params.status = status
    }

    // 处理频道
    // if (channel_id !== undefined) {
    if (typeof channel_id !== 'undefined') {
      params.channel_id = channel_id
    }

    // 日期范围
    if (typeof date !== 'undefined' && date !== null) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD HH:mm:ss')
      params.end_pubdate = date[1].format('YYYY-MM-DD HH:mm:ss')
    }
    // 将数据都存到useRef中
    paramsRef.current = params
    dispatch(getArticles(params))
  }
  // 分页的功能
  const changePage = (page, pageSize) => {
    // 分页数据
    const params = {
      page,
      per_page: pageSize,
    }
    // 分发获取数据的action
    dispatch(getArticles(params))
  }
  // 删除文章
  const onDeleteArticle = (id) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除该文章, 是否继续?',
      async onOk() {
        // 删除数据
        await dispatch(delArticle(id))
        // 删除数据后，再获取最新的文章列表数据
        await dispatch(getArticles(paramsRef.current))
      },
    })
  }

  return (
    <div>
      <Card
        title={
          <Breadcrumb seperator='>'>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: -1 }} onFinish={onSearch}>
          <FormItem label='状态' name='status'>
            <Radio.Group value={status}>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </FormItem>
          <FormItem label='频道' name='channel_id' style={{ width: 200 }}>
            <Select placeholder='请选择文章频道'>
              {channels.map((item) => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label='日期' name='date'>
            <RangePicker locale={locale}></RangePicker>
          </FormItem>
          <FormItem>
            <Button type='primary' htmlType='submit'>
              筛选
            </Button>
          </FormItem>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到 ${count} 条结果：`}>
        <Table
          rowKey='id'
          columns={columns}
          dataSource={list}
          pagination={{
            current: page,
            pageSize,
            total: count,
            showSizeChanger: true,
            position: ['bottomCenter'],
            onChange: changePage,
          }}
        />
      </Card>
    </div>
  )
}
export default Article
